// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import MeshDeform from "./MeshDeform";

const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Sprite)
    meshRenderer: cc.Sprite = null;

    start() {
        this.initMesh();
    }

    onChange() {
        this.play();
    }

    /**
     * 顶点列表
     */
    private vertexes: number[] = [
        352.97, 0,
        -259.03, 0,
        -259.03, 512,
        252.97, 512,
        -12.75, 245.6
    ];
    //uv
    private usv: number[] = [
        1, 1, 0, 1, 0, 0, 1, 0, 0.48101, 0.52032
    ];
    //索引
    private ids: number[] = [
        4, 2, 3, 1, 2, 4, 4, 3, 0, 1, 4, 0
    ];

    /**
     * 初始化网格信息
     */
    initMesh() {
        let vxs = [];
        let vys = [];
        let nus = [];
        let nvs = [];
        for (let i = 0, len = this.vertexes.length; i < len; i += 2) {
            vxs.push(this.vertexes[i]);
            vys.push(this.vertexes[i + 1]);
        }
        for (let i = 0, len = this.usv.length; i < len; i += 2) {
            nus.push(this.usv[i]);
            nvs.push(this.usv[i + 1]);
        }
        this.meshRenderer.spriteFrame.vertices = {
            x: vxs,
            y: vys,
            nu: nus,
            nv: nvs,
            triangles: this.ids,
        }
        // 标记顶点数据修改过了
        this.meshRenderer.setVertsDirty();

    }

    play() {
        let meshDeform = this.meshRenderer.getComponent(MeshDeform);
        meshDeform.loadAnimationsConfig({
            "move": [
                {},
                {
                    "time": 0.1667,
                    "offset": 2,
                    "vertices": [
                        -35.44797,
                        6.33002,
                        0,
                        0,
                        0,
                        0,
                        0,
                        76.47995
                    ]
                },
                {
                    "time": 0.5,
                    "vertices": [
                        -5.41607,
                        -71.76198,
                        29.78799,
                        50.09802,
                        31.14197,
                        62.28409,
                        -9.47798,
                        -81.24002
                    ]
                },
                {
                    "time": 0.6667
                }
            ],
        })
        meshDeform.playAction("move", true);
    }

}
